<template>
  <div>
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>书籍管理</el-breadcrumb-item>
      <el-breadcrumb-item>查看书籍</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <!-- 卡片展示区 -->
    <el-card class="box-card">
      <!-- 头部查询按钮 与 搜索框 开始 -->
      <div>
        <el-input
          class="searchBook my-el-input"
          placeholder="请输入作者或书名"
          style="width: 300px"
          v-model="queryBookCondition.search"
          clearable
        >
        </el-input
        ><el-button
          icon="el-icon-search"
          class="searchBookButton my-el-button"
          type="primary"
          @click="queryBookButton"
          >查询</el-button
        >
      </div>
      <!-- 头部查询按钮 与 搜索框 结束 -->
      <!-- 表格展示数据 开始 -->
      <el-table v-loading="loading" :data="bookTableData" style="width: 100%">
        <el-table-column fixed type="index" width="50"> </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="bookName"
          label="书籍名称"
          width="150"
        >
        </el-table-column>
        <el-table-column prop="bookAuthor" label="书籍作者" width="120">
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="bookIntroduction"
          label="书籍简介"
          width="120"
        >
        </el-table-column>
        <el-table-column prop="" label="书籍封面" width="120">
          <template slot-scope="scope">
            <img
              :src="scope.row.bookCover"
              width="80px"
              height="100px"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column prop="bookLaunchTime" label="书籍上架时间" width="155">
          <template slot-scope="scope">
            {{ scope.row.bookLaunchTime }}
          </template>
        </el-table-column>
        <el-table-column prop="bookEndOrSerial" label="完结或连载" width="120">
          <template slot-scope="scope">
            <div :class="scope.row.bookEndOrSerial == 2 ? 'end' : 'serial'">
              {{ scope.row.bookEndOrSerial == 1 ? '连载中' : '已完结' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="bookNumberOfWords" label="字数总数" width="120">
        </el-table-column>
        <el-table-column prop="bookNumberOfHits" label="点击数" width="120">
        </el-table-column>
        <el-table-column prop="bookToUpdate" label="最新更新时间" width="155">
          <template slot-scope="scope">
            {{
              scope.row.bookToUpdate == '1970-01-1 8:0:0'
                ? '暂无更新'
                : scope.row.bookToUpdate
            }}
          </template>
        </el-table-column>
        <el-table-column prop="bookGeneralSection" label="总章节" width="120">
        </el-table-column>
        <el-table-column prop="bookClassification" label="书籍分类" width="120">
        </el-table-column>
        <el-table-column prop="bookCollection" label="收藏数" width="120">
        </el-table-column>
        <el-table-column prop="bookStatus" label="书籍状态" width="120">
          <template slot-scope="scope">
            <el-dropdown @command="handleCommand">
              <el-button
                size="mini"
                :class="scope.row.bookStatus == 1 ? 'my-el-button' :''"
                :type="scope.row.bookStatus == 1 ? 'primary' : 'danger'"
              >
                {{ scope.row.bookStatus == 1 ? '上架中' : '已下架'
                }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  class="my-el-dropdown-item"
                  :command="composeValue(1, scope.row, 'bookStatus')"
                  >上架</el-dropdown-item
                >
                <el-dropdown-item
                class="my-el-dropdown-item"
                  :command="composeValue(0, scope.row, 'bookStatus')"
                  >下架</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="230">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="primary"
              @click="handleClick(scope.$index, scope.row)"
              >详情</el-button
            > -->
            <el-button size="mini" class="my-el-button-default" @click="handleEdit(scope.$index, scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格展示数据 结束 -->
      <!-- 分页 开始-->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryBookCondition.page"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="queryBookCondition.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 分页 结束-->
    </el-card>
    <!-- 修改弹出层 开始-->
    <el-dialog
      title="修改书籍详情"
      ref="updateForm"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="updateForm">
        <el-form-item label="书籍名称" :label-width="formLabelWidth">
          <el-input
            disabled=""
            v-model="updateForm.bookName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="书籍作者" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.bookAuthor"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="书籍封面" :label-width="formLabelWidth">
          <el-upload
            ref="uploadImg"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="changeUpload"
            :file-list="fileList"
            :http-request="uploadImg"
          >
            <img
              v-if="updateForm.bookCover"
              :src="imgUrl || updateForm.bookCover"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="书籍上架时间" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
              disabled
              v-model="updateForm.bookLaunchTime"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="书籍分类" :label-width="formLabelWidth">
          <el-select
            v-model="updateForm.bookClassification"
            placeholder="请选择"
          >
            <el-option
              v-for="item in bookClassification"
              :key="item._id"
              :label="item.classificationName"
              :value="item.classificationName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="书籍完结或连载" :label-width="formLabelWidth">
          <el-dropdown @command="endCommand">
            <el-button
              size="mini"
              :type="updateForm.bookEndOrSerial == 1 ? 'info' : 'success'"
            >
              {{ updateForm.bookEndOrSerial == 1 ? '连载中' : '已完结'
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
              class="my-el-dropdown-item"
                :command="composeValue(1, updateForm, 'bookEndOrSerial')"
                >连载</el-dropdown-item
              >
              <el-dropdown-item
              class="my-el-dropdown-item"
                :command="composeValue(2, updateForm, 'bookEndOrSerial')"
                >完结</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item label="字数总数" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.bookNumberOfWords"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="点击总数" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.bookNumberOfHits"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="最新更新时间" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.bookToUpdate"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="总章节" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.bookGeneralSection"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="书籍收藏" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.bookCollection"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="书籍状态" :label-width="formLabelWidth">
          <el-dropdown @command="handleCommand">
            <el-button
              size="mini"
              :type="updateForm.bookStatus == 1 ? 'primary' : 'danger'"
            >
              {{ updateForm.bookStatus == 1 ? '上架中' : '已下架'
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                class="my-el-dropdown-item"
                :command="composeValue(1, updateForm, 'bookStatus')"
                >上架</el-dropdown-item
              >
              <el-dropdown-item
              class="my-el-dropdown-item"
                :command="composeValue(0, updateForm, 'bookStatus')"
                >下架</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item label="书籍简介" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="4"
            v-model="updateForm.bookIntroduction"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelButton">取 消</el-button>
        <el-button type="primary" @click="modifyBookbutton">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改弹出层 结束 -->
  </div>
</template>
<script>
import {
  bookQueryPage,
  bookModify,
  bookQueryTotal,
  uploadImg,
  uploadImgTrue,
  getBookClassification
} from '@/network/bookManager'
import { timeStampFormatStr } from '@/util/dataTimeUtil'
export default {
  data() {
    return {
      bookTableData: [],
      isBookStatus: true,
      total: 10,
      loading: true, // 加载动画
      dialogFormVisible: false, // 弹出层状态
      // 条件对象
      queryBookCondition: {
        page: 1,
        size: 5,
        search: '',
        authorId: ''
      },
      // 修改表单 数据
      updateForm: {
        _id: '',
        bookName: '',
        bookLaunchTime: '',
        bookIntroduction: '',
        bookClassification: '',
        bookAuthor: '',
        bookCover: '',
        authorId: '',
        bookCollection: 0,
        bookEndOrSerial: 1,
        bookGeneralSection: 0,
        bookNumberOfHits: 0,
        bookNumberOfWords: 0,
        bookStatus: 1,
        bookToUpdate: ''
      },
      formLabelWidth: '120px', // 表单元素宽度
      fileList: [],
      file: null, // 文件
      imgUrl: '',
      imgUrlCup: '', // 空杯图片地址
      // 书籍分类
      bookClassification: [],
      // 角色
      role: {},
      // 账户
      user: {}
    }
  },
  methods: {
    // 查看书籍详情
    handleClick(index, row) {
      console.log(row)
    },
    // 修改按钮
    handleEdit(index, row) {
      this.dialogFormVisible = true // 开启显示 弹出层
      this.updateForm = row
      console.info(row)
    },
    // 删除按钮
    handleDelete(index, row) {
      this.changeStatus(row, 3, 'bookStatus')
    },
    // 时间戳 转时间
    timeStampFormatStr,
    // 计算属性
    calculation(status) {
      return status == 1 ? true : false
    },
    //  修改方法 状态改变方法
    changeStatus(row, e, name) {
      console.info(row)
      this.$confirm(
        `此操作将${
          name == 'bookStatus' && e == 3 ? `删除` : `修改`
        }该信息, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          if (this.imgUrlCup) row.bookCover = this.imgUrlCup
          if (name == 'bookStatus') row.bookStatus = e // 修改上架或下架状态
          if (name == 'bookEndOrSerial') row.bookEndOrSerial = e // 修改 连载或完结状态
          await bookModify(row) // 修改书籍
          this.$message.success('修改成功')
          if (name == 'bookStatus' || name == 'modifyButton') {
            this.dialogFormVisible = false // 关闭弹出层
          }
          // 只有修改 书籍状态为3  以及点击 确定按钮时 才从新查询书籍
          if ((name == 'bookStatus' && e != 3) || name == 'bookEndOrSerial')
            return
          this.queryBook() // 重新查询书籍
          // this.imgUrl
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })
    },
    // size数据改变
    handleSizeChange(val) {
      this.queryBookCondition.size = val
    },
    // 翻页
    handleCurrentChange(val) {
      this.queryBookCondition.page = val
    },
    // 查询书籍信息
    async queryBook() {
      this.loading = true // 开启loading
      if (this.role.roleName != '超级管理员') {
        this.queryBookCondition.authorId = this.user._id
      }

      let res = await bookQueryPage(this.queryBookCondition)
      console.info(res)
      let resTotal = await bookQueryTotal(this.queryBookCondition)
      if (res.errcode !== 0 || res.errmsg != 'ok')
        return this.$message.warning('页面加载错误，请刷新当前页面')
      this.bookTableData = [] // 置空原数据
      this.total = resTotal.count // 设置总数
      for (let rs in res.data) {
        this.bookTableData.push(JSON.parse(res.data[rs]))
        this.bookTableData[rs].bookLaunchTime = this.timeStampFormatStr(
          this.bookTableData[rs].bookLaunchTime.$date
        )
        this.bookTableData[rs].bookToUpdate =
          this.timeStampFormatStr(this.bookTableData[rs].bookToUpdate.$date) ==
          '1970-01-1 8:0:0'
            ? '暂无更新'
            : this.timeStampFormatStr(this.bookTableData[rs].bookToUpdate.$date)
      }
      this.loading = false // 关闭loading
    },
    // 查询按钮
    queryBookButton() {
      this.queryBook()
    },
    // 图片上传成功后的回调
    handleAvatarSuccess() {
      this.$message.success('创建成功')
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    changeUpload(file, fileList) {
      this.file = file
      console.info(file)
      const isJPG = new RegExp('^image/.*$').test(file.raw.type)
      const isLt2M = file.raw.size / 1024 / 1024 < 2
      this.fileList = fileList
      if (isJPG && isLt2M) {
        this.imgUrl = URL.createObjectURL(file.raw)
        this.fileList.length > 1 ? this.fileList.splice(0, 1) : ''
        this.oldFileUid = file.uid
      } else {
        this.fileList.length > 1
          ? this.fileList.splice(1, 1)
          : this.fileList.splice(0, 1)
        if (!isJPG) {
          this.$message.error('只能上传图片哦')
        } else if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
      }
      return isJPG && isLt2M
      // console.info( this.imgUrl)
    },
    // 自定义上传方法
    async uploadImg() {
      let file = this.file
      this.imgUrlCup = ''
      const isJPG = new RegExp('^image/.*$').test(file.raw.type)
      if (!isJPG) return
      const imgName =
        `boxContent/${this.updateForm.bookName}/novelimg/` +
        new Date().getTime() +
        file.name
      let res = await uploadImg(imgName)
      // 将返回的地址 处理成代理地址
      let website = res.url.substring(0, res.url.indexOf('com') + 3)
      let trueUrl = res.url.replace(website, '/img')
      // 将数据封装成 formData
      const formData = new FormData()
      formData.append('Signature', res.authorization)
      formData.append('key', imgName)
      formData.append('x-cos-security-token', res.token)
      formData.append('x-cos-meta-fileid', res.cos_file_id)
      formData.append('file', file.raw)
      uploadImgTrue(trueUrl, formData) // 最后一步上传图片
      const imgUrl = `https://7a68-zhuma-mbnti-1302831863.tcb.qcloud.la/${imgName}`
      this.imgUrlCup = imgUrl
      //this.updateForm.bookCover =imgUrl // 将图片路径 存入表单对象中
      console.info(imgUrl)
      console.info(this.imgUrl)
    },
    // 菜单指令 修改下架与上架
    handleCommand(command) {
      console.info(command)
      if (command.book.bookStatus != command.item) {
        this.changeStatus(command.book, command.item, command.name)
      }
    },
    // dropdown 获取额外参数方法
    composeValue(item, book, name) {
      return {
        item,
        book,
        name
      }
    },
    // 修改连载 或完结
    endCommand(command) {
      if (command.book.bookEndOrSerial != command.item) {
        this.changeStatus(command.book, command.item, command.name)
      }
    },
    // 修改书籍 按钮
    modifyBookbutton() {
      this.changeStatus(this.updateForm, undefined, 'modifyButton')
    },
    // 取消按钮
    cancelButton() {
      this.dialogFormVisible = false
      this.imgUrl = ''
      this.queryBook()
    }
  },
  // 监听属性
  watch: {
    'queryBookCondition.page': {
      // 页码发生变化
      handler: function() {
        this.queryBook()
      }
    },
    'queryBookCondition.size': {
      // 每页多少条发生变化
      handler: function() {
        this.queryBook()
      }
    },
    dialogFormVisible: {
      handler: function() {
        if (this.dialogFormVisible) return
        this.imgUrl = ''
        this.queryBook()
      }
    }
  },
  // vue 生命周期方法
  async mounted() {
    this.role = JSON.parse(sessionStorage.getItem('role'))
    console.info( this.role)
    this.user =  JSON.parse(sessionStorage.getItem('user'))
    this.queryBook()
    let res = await getBookClassification()
    this.bookClassification = []
    for (let rs in res.data) {
      this.bookClassification.push(JSON.parse(res.data[rs]))
    }

    console.info(res)
  }
}
</script>
<style lang="less" scoped>
.searchBookButton {
  width: 100px;
}
.el-dialog__title {
  color: #409eff !important;
}
.el-dialog__header {
  color: #409eff !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #409eff;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.select {
  background-color: #409eff;
  color: #fff;
}
.el-input__inner {
  background-color: currentColor;
}
.end {
  color: #67c23a;
}
</style>
